﻿#include "clientcorrespond.h"
#include <QDebug>

ClientCorrespond::ClientCorrespond(QObject *parent) : QObject(parent)
{
    
}


void ClientCorrespond::init()
{
    socket = new QTcpSocket(this);
    control = new Forward_Control(this);
    qRegisterMetaType<CONNECT_STATUS>("CONNECT_STATUS");
    qRegisterMetaType<QAbstractSocket::SocketError>("SocketError");//注册ForwardInfo类型
}


void ClientCorrespond::connectToServer()
{
    if(socket == nullptr || control == nullptr)
    {
        init();
    }
    qDebug()<<"获取服务器信息";
    QString ip = Forward_Config::GetServerHost();
    int port = Forward_Config::GetServerPort();
    int timeout = Forward_Config::GetTimeoutSecond()*1000;
    QAbstractSocket::SocketState state = socket->state();
    
    qDebug()<<"等待连接";
    emit connectStateChange(CONNECT_STATUS::WAIT);
    if(state != socket->UnconnectedState)
    {
        //当前状态不是非连接状态，发送等待信号让用户等一下
        qDebug()<<"当前状态非断开状态 state: "<<state;
        return;
    }
    
    qDebug()<<"连接服务器";
    socket->connectToHost(QHostAddress(ip),port);
    if(!socket->waitForConnected(timeout))
    {
        qDebug()<<"连接失败";
        emit connectStateChange(CONNECT_STATUS::FAILED); 
    }else {
        qDebug()<<"连接成功";
        emit connectStateChange(CONNECT_STATUS::SUCCESS);
        connect(socket,&QTcpSocket::readyRead,this,&ClientCorrespond::recvResponse);
        connect(socket,&QTcpSocket::disconnected,this,&ClientCorrespond::stopServer);
    }
    
}

void ClientCorrespond::stopServer()
{
    qDebug()<<"断开中央服务器连接";
    socket->disconnectFromHost();
    socket->close();
    emit connectStateChange(CONNECT_STATUS::DONE);
}

void ClientCorrespond::openPort(QJsonObject info)
{
    if(socket->state() != QTcpSocket::ConnectedState)
    {
        return;
    }
    qDebug()<<"发送打开端口的报文";
    
    QJsonObject obj;
    
    obj["control"] = NEWPORT.data();
    obj["info"] = info;
    qDebug()<<"发送报文";
    QByteArray sBuffer = QJsonDocument(obj).toJson();
    qDebug()<<sBuffer;
    socket->write(sBuffer);
}

void ClientCorrespond::closePort(QJsonObject info)
{
    if(socket->state() != QTcpSocket::ConnectedState)
    {
        return;
    }
    qDebug()<<"发送打开端口的报文";

    QJsonObject obj;
    obj["control"] = CLOSEPORT.data();
    obj["info"] = QJsonDocument(info).toJson().data();
    
    socket->write(QJsonDocument(obj).toJson());
}

void ClientCorrespond::recvResponse()
{
    
    QByteArray buffer = socket->readAll();
    qDebug()<<"接收服务器报文";
    qDebug()<<buffer;
    
    QJsonParseError error;
    QJsonDocument document = QJsonDocument::fromJson(buffer,&error);  //解析回传的对象
    if(error.error != QJsonParseError::NoError)
    {
        qDebug()<<"报文解析失败: "<<buffer;
        return;
    }
    QJsonObject obj = document.object();
    
    QByteArray command = obj["command"].toString().toUtf8();
    QByteArray message = obj["message"].toString().toUtf8();
    QJsonObject info = obj["info"].toObject();
    
    if(command == ADDSERVICE)
    {
        //增加服务数量
        qDebug()<<"增加服务器数量";
        for (int var = 0; var < 3; var++) {
            control->openPort(info);
        }
        control->openPort(info);
    }else if(message == PORTOPEN)
    {
        //开启10个使用端口
        qDebug()<<"第一次增加3个服务器数量";
        for (int var = 0; var < 3; var++) {
            control->openPort(info);
        }
        emit forwardStatusChange(info["forwardPort"].toString().toInt(),CONNECT_STATUS::SUCCESS);
    }else if(message == CLOSEPORT){
        emit forwardStatusChange(info["forwardPort"].toString().toInt(),CONNECT_STATUS::DONE);
    }else
    {
        qDebug()<<"command: "<<obj["command"].toString();
        qDebug()<<"message: "<<obj["message"].toString();
        qDebug()<<"errmsg: "<<obj["errmsg"];
    }
    
}
